package com.demo.juc.futuretask;

import java.util.concurrent.*;

/**
 * @Author: shubin_yao
 * @Date: 2022/09/25/8:59
 * @Description: FutureTask  常用方案  及存在问题
 * <p>
 * get() 阻塞
 * get(,)  粗暴
 * isDone() 回调 耗时
 */
public class FutureTaskApi {

    public static void main(String[] args) throws Exception {

        //用FutureTask 异步处理一个任务，耗时5s
        FutureTask<String> futureTask = new FutureTask<>(new MyThread());

        new Thread(futureTask, "t1").start();

        //System.out.println(futureTask.get());   //阻塞，等不到结果就一直等着
        //System.out.println(futureTask.get(3, TimeUnit.SECONDS));  //等不到结果，强制抛异常

        // 轮询调，造成CPU资源消耗
        while (true) {
            if (futureTask.isDone()) {
                System.out.println(futureTask.get());
                break;
            } else {
                System.out.println("请稍后。。。");
            }
        }

        System.out.println(Thread.currentThread().getName() + "执行完毕");

    }


    /**
     * 实现call方法的接口
     */
    static class MyThread implements Callable<String> {
        @Override
        public String call() throws Exception {
            System.out.println("come in 。。。");
            TimeUnit.SECONDS.sleep(5);
            return "game over!";
        }
    }
}
